from DrissionPage import Chromium
from DrissionPage.errors import ElementNotFoundError
from flask import jsonify
from loguru import logger
from DrissionPage.common import Keys
def update_status_by_id(connection, table_id, status, fail_reason=None):
    try:
        if connection and table_id:
            with connection.cursor() as cursor:
                if fail_reason is not None:
                    sql = "UPDATE jg_campaign_bid_operate SET status = %s, fail_reason = %s WHERE id = %s"
                    params = (status, fail_reason, table_id)
                else:
                    sql = "UPDATE jg_campaign_bid_operate SET status = %s WHERE id = %s"
                    params = (status, table_id)

                cursor.execute(sql, params)
                connection.commit()
                logger.info(f"成功更新 ID={table_id} 的 status 为 {status}")
        else:
            logger.warning("未提供有效的数据库连接或 table_id 为空")
    except Exception as e:
        logger.error(f"更新状态失败: {str(e)}")
        connection.rollback()
def start_auto_bid(plan_tab, every_row_data, connection=None):
    try:
        table_id = every_row_data.get('id')
        campaign_id = every_row_data.get('campaign_id')
        event_bid = every_row_data.get('event_bid')

        plan_tab.ele('tag:span@@class=d-text --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis@@text()=计划ID').parent(4).click(by_js=True)
        plan_tab.ele('tag:input@@class=d-text@@placeholder=请输入计划ID').input(campaign_id, clear=True).wait(0.5).input(Keys.ENTER)

        body_tr_ele = None

        # 一直等待当前计划被查出来
        while True:
            body_tr_ele = plan_tab.ele('tag:tbody@@class=d-table__body').eles('tag:tr')
            if len(body_tr_ele) == 1:
                break
            plan_tab.wait(1)

        body_tr_ele[0].ele('tag:a@@class=d-text d-link --color-primary --size-text-paragraph link-color@@text()=详情', timeout=2).click(by_js=True)
        plan_tab.ele('tag:span@@class=d-text --color-text-paragraph --size-text-small unit-card-label@@text()=目标成本').next().next().click(by_js=True)

        plan_tab.ele('tag:h6@@text()=修改目标成本').wait.displayed()
        plan_tab.ele('tag:div@@class=d-modal-content').ele('.d-form-item__content').ele('tag:input@@class=d-text@@placeholder=请输入').input(event_bid, clear=True)

        # plan_tab.ele('tag:span@@text()=保存修改').parent(2).click(by_js=True)
        # plan_tab.ele('tag:span@@text()=取消').parent(2).click(by_js=True)

        # 更新数据库表的状态值
        update_status_by_id(connection, table_id, status=1)
    except ElementNotFoundError as e:
        logger.error(f"错误类型: {type(e).__name__}\n "f"错误详情: {str(e)}")
        update_status_by_id(connection, table_id, status=2, fail_reason=f"没有找到元素:{str(e)}")
    except Exception as e:
        logger.error(f"错误类型: {type(e).__name__}\n "f"错误详情: {str(e)}")
        update_status_by_id(connection, table_id, status=2)

def handle_queue_data_to_auto_bid(queue=None, plan_tab=None, connection=None):
    try:
        if queue is None:
            return

        while not queue.empty():
            every_row_data = queue.get()
            logger.info(f"当前线程拿到的当前行数据:{every_row_data}")
            start_auto_bid(plan_tab, every_row_data, connection)
    except Exception as e:
        # 日志记录完整错误
        logger.error(f"错误类型: {type(e).__name__}\n "f"错误详情: {str(e)}")
        return jsonify({'error': str(e)}), 500


if __name__ == '__main__':
    browser = Chromium()
    plan_tab = browser.new_tab('https://ad.xiaohongshu.com/aurora/ad/manage/campaign?vSellerId=63e5ae80f2eae80001efe3d6')

    data = {'id': 3629, 'time': '2025-05-09 16:50:01', 'advertiser_id': 216518, 'seller_id': '63e5ae80f2eae80001efe3d6', 'campaign_id': 115451725, 'unit_id': 232068610, 'fee': 179817, 'before_event_bid': 90, 'event_bid': 0.85, 'before_campaign_enable': 1, 'campaign_enable': 1, 'type': 2, 'status': 0, 'fail_reason': None, 'del_flag': 0}
    start_auto_bid(plan_tab, data)
